# coding=utf-8
# 编译日期：2020-03-19 14:16:10
# 版权所有：www.i-search.com.cn
import time
import pdb
from ubpa.ilog import ILog
from ubpa.base_img import *
import getopt
from sys import argv
import sys
from win32com.client.gencache import EnsureDispatch
import base64
import json
import os
import pandas as pd
import shutil
import ubpa.ibox as ibox
import ubpa.iexcel as iexcel
import ubpa.ifile as ifile
import ubpa.imail as imail
import ubpa.itools.rpa_fun as rpa_fun
import ubpa.itools.rpa_str as rpa_str
import ubpa.itools.rpa_time as rpa_time

class email_assistant:
     
    def __init__(self,**kwargs):
        self.__logger = ILog(__file__)
        self.path = set_img_res_path(__file__)
        self.robot_no = ''
        self.proc_no = ''
        self.job_no = ''
        self.input_arg = ''
        self.mail_pwd=None
        self.mail_id=None
        self.authorization_code=None
        self.mail_type=None
        self.file_path=None
        self.mail_information=None
        if('robot_no' in kwargs.keys()):
            self.robot_no = kwargs['robot_no']
        if('proc_no' in kwargs.keys()):
            self.proc_no = kwargs['proc_no']
        if('job_no' in kwargs.keys()):
            self.job_no = kwargs['job_no']
        if('input_arg' in kwargs.keys()):
            self.input_arg = kwargs['input_arg']
            self.input_arg = self.input_arg.replace("\\","/")
            self.mail_pwd = json.loads(base64.b64decode(self.input_arg))['mail_pwd']
            self.mail_id = json.loads(base64.b64decode(self.input_arg))['mail_id']
            self.authorization_code = json.loads(base64.b64decode(self.input_arg))['authorization_code']
            self.mail_type = json.loads(base64.b64decode(self.input_arg))['mail_type']
            self.file_path = json.loads(base64.b64decode(self.input_arg))['file_path']
            self.mail_information = json.loads(base64.b64decode(self.input_arg))['mail_information']
      
    def mail_result(self,return_1=None):
        file=None
        timetime=None
        # Try异常
        self.__logger.debug('Flow:mail_result,StepNodeTag:12131118074363,Note:子流程容错')
        try:
            #当前日期
            self.__logger.debug('Flow:mail_result,StepNodeTag:12131452223374,Note:获取当前时间')
            timetime = rpa_time.get_current_datetime_str(format='%Y%m%d%H%M%S')
            # 代码块
            self.__logger.debug('Flow:mail_result,StepNodeTag:181747066153,Note:删掉缓存文件')
            xl = EnsureDispatch("Word.Application")
            file_path=os.path.abspath(os.path.dirname(os.path.dirname(sys.modules[xl.__module__].__file__)))
            listpath=os.listdir(file_path)
            for i in listpath:
                if '.' not in i:
                    target_file=i
            try:
                shutil.rmtree(os.path.join(file_path,target_file))
            except:
                pass
            #创建excel
            self.__logger.debug('Flow:mail_result,StepNodeTag:17144831727117,Note:创建结果文件')
            file = iexcel.create_excel(path=self.file_path,file_name='发送邮件结果_'+timetime)
            #单元格写入
            self.__logger.debug('Flow:mail_result,StepNodeTag:12132546977403,Note:输入执行结果')
            iexcel.write_cell(path=file,text=return_1,file_type='excel')
            #插入行
            self.__logger.debug('Flow:mail_result,StepNodeTag:12132753059414,Note:加上表头')
            iexcel.ins_row(path=file,data=['收件人邮箱','收件人称呼','邮件主题','正文','附件（文件名+格式）','发送状态','备注'],file_type='excel')
        except Exception as e:
            # Return返回
            self.__logger.debug('Flow:mail_result,StepNodeTag:12131137509364,Note:')
            return 'err'
        finally:
            pass
      
    def mail_sent(self):
        att_i_i=None
        att_i=None
        att_split=None
        att_list=None
        att=None
        file_path=None
        return_list=None
        m_topic=None
        m_text=None
        m_receiver_add=None
        line_data=None
        m_attchment=None
        data=None
        num=None
        server_add=None
        # Try异常
        self.__logger.debug('Flow:mail_sent,StepNodeTag:121022550145,Note:子流程容错')
        try:
            # IF-N分支
            self.__logger.debug('Flow:mail_sent,StepNodeTag:121022280133,Note:判断邮箱种类')
            if self.mail_type == '腾讯企业邮箱':
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:121024216088,Note:企业邮箱服务器')
                server_add='smtp.exmail.qq.com'
            elif self.mail_type == '腾讯qq邮箱':
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:1210244481613,Note:腾讯qq邮箱服务器')
                server_add='smtp.qq.com'
            elif self.mail_type == '163邮箱':
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:1210244513717,Note:163邮箱服务器')
                server_add='smtp.163.com'
            else:
                pass
            #读取Excel
            self.__logger.debug('Flow:mail_sent,StepNodeTag:1210544642063,Note:读取配置文件')
            data = pd.read_excel(io=self.mail_information)
            # 设置值
            self.__logger.debug('Flow:mail_sent,StepNodeTag:1611041654422,Note:无附件制空')
            data=data.fillna('')
            # 设置值
            self.__logger.debug('Flow:mail_sent,StepNodeTag:12112816922182,Note:设定一个空列表')
            return_list=[]
            # For循环
            self.__logger.debug('Flow:mail_sent,StepNodeTag:1210551598071,Note:循环读取每行内容')
            for i in data.iterrows():
                # 序列
                self.__logger.debug('Flow:mail_sent,StepNodeTag:12121621923351,Note:')
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:1211024743481,Note:设置数据位置变量')
                num=i[0]
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:1211034838987,Note:设置每行内容变量')
                line_data=i[1].values.tolist()
                # IF-N分支
                self.__logger.debug('Flow:mail_sent,StepNodeTag:17135326295103,Note:判断附件分割符号')
                if ',' in line_data[4]:
                    #split
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:171319095672,Note:英文逗号分隔处理')
                    att_split = rpa_str.split(string=line_data[4],str=',')
                    # 设置值
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:1713240596518,Note:制空列表')
                    att_list=[]
                    # For循环
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:171319524154,Note:循环每个附件')
                    for att in att_split:
                        # 设置值
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1210364975446,Note:设置附件变量')
                        att=os.path.join(self.file_path,att)
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1713230044716,Note:拼接所有附件路径')
                        att_list = rpa_fun.list_append(list=att_list,obj=att)
                    #join
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:1713251319135,Note:用逗号拼接附件路径')
                    m_attchment = rpa_str.join(string=',',iterable=att_list)
                elif '，' in line_data[4]:
                    #split
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:1713304639452,Note:英文逗号分隔处理')
                    att_split = rpa_str.split(string=line_data[4],str='，')
                    # 设置值
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:17135715161125,Note:制空列表')
                    att_list=[]
                    # For循环
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:17135715161130,Note:循环每个附件')
                    for att in att_split:
                        # 设置值
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:17135715161128,Note:设置附件变量')
                        att=os.path.join(self.file_path,att)
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:17135715161126,Note:拼接所有附件路径')
                        att_list = rpa_fun.list_append(list=att_list,obj=att)
                    #join
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:17135715160120,Note:用逗号拼接附件路径')
                    m_attchment = rpa_str.join(string=',',iterable=att_list)
                else:
                    # 设置值
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:1810434624510,Note:设置附件变量')
                    m_attchment=os.path.join(self.file_path,line_data[4])
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:12111216724104,Note:设置收件人地址变量')
                m_receiver_add=line_data[0]
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:12111543642111,Note:设置收件人称呼加正文变量')
                m_text=line_data[1]+line_data[3]
                # 设置值
                self.__logger.debug('Flow:mail_sent,StepNodeTag:12111746152115,Note:设置收件人称呼加正文变量')
                m_topic=line_data[2]
                # IF-N分支
                self.__logger.debug('Flow:mail_sent,StepNodeTag:12111919499130,Note:判断是否需要发送附件')
                if line_data[4]=='':
                    # Try异常
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:1611364982833,Note:发送邮件容错')
                    try:
                        #发送邮件
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12111919499131,Note:发送邮件')
                        imail.send_smtp_mail(server=server_add,port=465,ssl='yes',sender=self.mail_id,receivers=m_receiver_add,psw=self.mail_pwd,subject=m_topic,body=m_text,method='text')
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12112259178148,Note:添加发送状态信息')
                        line_data = rpa_fun.list_append(list=line_data,obj='已发送')
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12112414381155,Note:添加备注信息')
                        line_data = rpa_fun.list_append(list=line_data,obj='无')
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12112726094177,Note:将发送状态与备注汇总')
                        return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                    except Exception as e:
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1611462628853,Note:添加发送状态信息')
                        line_data = rpa_fun.list_append(list=line_data,obj='未发送')
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1611462628852,Note:添加备注信息')
                        line_data = rpa_fun.list_append(list=line_data,obj='发送邮件出现错误')
                        #append
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1611462628851,Note:将发送状态与备注汇总')
                        return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                    finally:
                        pass
                else:
                    # IF-N分支
                    self.__logger.debug('Flow:mail_sent,StepNodeTag:171423309903,Note:判断附件是否有多个')
                    if type(att_list)==list:
                        # For循环
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:171424227307,Note:循环遍历每个附件是否匹配')
                        for att_i in att_list:
                            #文件是否存在
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714262588017,Note:判断附件是否存在')
                            tvar1714262588017 = ifile.exist_file(filename=att_i)
                            # IF-N分支
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714260099215,Note:')
                            if tvar1714262588017:
                                # Continue继续
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714370703537,Note:')
                                continue
                            else:
                                # 设置值
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714382263740,Note:')
                                att_i_i=1
                        # IF-N分支
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:1714392308645,Note:判断附件中是否有不匹配内容')
                        if att_i_i==1:
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714410991546,Note:添加发送状态信息')
                            line_data = rpa_fun.list_append(list=line_data,obj='未发送')
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714410991547,Note:添加备注信息')
                            line_data = rpa_fun.list_append(list=line_data,obj='附件内容未完全匹配')
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714410991652,Note:将发送状态与备注汇总')
                            return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                        else:
                            # Try异常
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582691,Note:发送邮件容错')
                            try:
                                #发送邮件
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582690,Note:发送邮件')
                                imail.send_smtp_mail(server=server_add,port=465,ssl='yes',sender=self.mail_id,receivers=m_receiver_add,psw=self.mail_pwd,subject=m_topic,body=m_text,attachments=m_attchment,method='text')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582679,Note:添加发送状态信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='已发送')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582680,Note:添加备注信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='无')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582685,Note:将发送状态与备注汇总')
                                return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                            except Exception as e:
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582678,Note:添加发送状态信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='发送失败')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582677,Note:添加备注信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='发送过程中出现异常')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:1714432582672,Note:将发送状态与备注汇总')
                                return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                            finally:
                                pass
                    else:
                        #文件是否存在
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12111919499124,Note:判断附件是否存在')
                        tvar12111919499124 = ifile.exist_file(filename=m_attchment)
                        # IF-N分支
                        self.__logger.debug('Flow:mail_sent,StepNodeTag:12111919499123,Note:判断附件是否存在')
                        if tvar12111919499124:
                            # Try异常
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:12111919499128,Note:发送邮件容错')
                            try:
                                #发送邮件
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113613303213,Note:发送邮件')
                                imail.send_smtp_mail(server=server_add,port=465,ssl='yes',sender=self.mail_id,receivers=m_receiver_add,psw=self.mail_pwd,subject=m_topic,body=m_text,attachments=m_attchment,method='text')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113645165232,Note:添加发送状态信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='已发送')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113645165231,Note:添加备注信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='无')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113645165226,Note:将发送状态与备注汇总')
                                return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                            except Exception as e:
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113754504244,Note:添加发送状态信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='发送失败')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113754504245,Note:添加备注信息')
                                line_data = rpa_fun.list_append(list=line_data,obj='发送过程中出现异常')
                                #append
                                self.__logger.debug('Flow:mail_sent,StepNodeTag:12113754504250,Note:将发送状态与备注汇总')
                                return_list = rpa_fun.list_append(list=return_list,obj=line_data)
                            finally:
                                pass
                        else:
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:12113846411275,Note:添加发送状态信息')
                            line_data = rpa_fun.list_append(list=line_data,obj='未发送')
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:12113846411274,Note:添加备注信息')
                            line_data = rpa_fun.list_append(list=line_data,obj='附件不存在')
                            #append
                            self.__logger.debug('Flow:mail_sent,StepNodeTag:12113846411269,Note:将发送状态与备注汇总')
                            return_list = rpa_fun.list_append(list=return_list,obj=line_data)
            #输出
            self.__logger.debug('Flow:mail_sent,StepNodeTag:12114240037294,Note:')
            rpa_str.iprint(param=return_list)
            # Return返回
            self.__logger.debug('Flow:mail_sent,StepNodeTag:12133747187419,Note:返回最终结果内容')
            return return_list
        except Exception as e:
            # Return返回
            self.__logger.debug('Flow:mail_sent,StepNodeTag:12114002069287,Note:')
            return 'err'
        finally:
            pass
      
    def Main(self):
        return2=None
        return1=None
        #消息框
        self.__logger.debug('Flow:Main,StepNodeTag:191330346362,Note:')
        ibox.msg_box(msg='  《邮件发送助手机器人》即将开始工作，机器人将会以模拟人手工操作的模式执行流程，请保存关闭正在打开的excel。\n  机器人会根据处理文件的数量级，进行不同时间长度的工作，您对电脑的其他操作，可能打断机器人的正常运行。\n  备注：Ctrl+Shift+B 终止机器人操作',timeout=10)
        # 子流程:mail_sent
        self.__logger.debug('Flow:Main,StepNodeTag:12132301428384,Note:发送邮件流程')
        (return1)=self.mail_sent()
        # IF-N分支
        self.__logger.debug('Flow:Main,StepNodeTag:121410153793,Note:判断发送邮件流程是否出现异常')
        if return1 != 'err':
            # 子流程:mail_result
            self.__logger.debug('Flow:Main,StepNodeTag:12132423822394,Note:流程结果文件创建')
            (return2)=self.mail_result(return_1=return1)
            # IF-N分支
            self.__logger.debug('Flow:Main,StepNodeTag:0415081996045,Note:判断创建结果流程是否出现异常')
            if return2 == 'err':
                #消息框
                self.__logger.debug('Flow:Main,StepNodeTag:0415082933750,Note:')
                ibox.msg_box(msg='发送状态创建失败')
            else:
                #消息框
                self.__logger.debug('Flow:Main,StepNodeTag:0415083987954,Note:')
                ibox.msg_box(msg='运行完成，请查看运行结果')
        else:
            #消息框
            self.__logger.debug('Flow:Main,StepNodeTag:130915578514,Note:')
            ibox.msg_box(msg='邮件发送过程出现异常！')
 
if __name__ == '__main__':
    robot_no = ''
    proc_no = ''
    job_no = ''
    input_arg = ''
    try:
        argv = sys.argv[1:]
        opts, args = getopt.getopt(argv,"hr:p:j:i:",["robot = ","proc = ","job = ","input = "])
    except getopt.GetoptError:
        print ('robot.py -r <robot> -p <proc> -j <job>')
    for opt, arg in opts:
        if opt == '-h':
            print ('robot.py -r <robot> -p <proc> -j <job>')
        elif opt in ("-r", "--robot"):
            robot_no = arg
        elif opt in ("-p", "--proc"):
            proc_no = arg
        elif opt in ("-j", "--job"):
            job_no = arg
        elif opt in ("-i", "--input"):
            input_arg = arg
    pro = email_assistant(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg)
    pro.Main()
